import { Http } from "@/utils/http";
import { getMessageApi } from "@/utils/messageHolder";
import { getRouter } from "@/router/index";

/** 通用错误处理 */
const handleError = (error: any) => {
  const msgApi = getMessageApi();
  const errMsg = error.response?.data?.message || error.message || "未知错误";
  if (msgApi) {
    msgApi.error(errMsg, 5);
  } else {
    import("antd").then(({ message }) => message.error(errMsg));
  }
};

/** 网络错误处理 */
const handleErrorNetwork = () => {
  const route = getRouter();
  route.navigate("/error");
};

/** token刷新失效处理 */
const handleTokenInvalidation = () => {
  const route = getRouter();
  route.navigate("/login");
};

const baseUrl = import.meta.env.VITE_BASE_URL;
const timeout = Number(import.meta.env.VITE_TIMEOUT);
export const http = new Http({ baseUrl, timeout, handleError, handleErrorNetwork, handleTokenInvalidation });
